from datetime import timedelta, datetime
from typing import Union

from jose import jwt
from loguru import logger
from sqlalchemy.orm import Session

from backend_module.dao.sys_user_dao import SysUserDao
from config.env import JwtConfig
from utils.pwd_util import PwdUtil
from utils.response_util import LoginException


class SysLoginService:
    @classmethod
    def sys_account_login_service(cls, db: Session, username: str, password: str):
        account = SysUserDao.get_user_by_login_info(db, username)
        if not account:
            logger.warning("User not found")
            raise LoginException(data="", message="用户不存在")
        if not PwdUtil.verify_password(password, account.login_password):
            logger.warning("wrong password")
            raise LoginException(data="", message="密码错误")

        return account

    @classmethod
    def get_user_by_id_service(cls, db: Session, user_id: int):
        result = SysUserDao.get_user_by_id(db, user_id)
        account = {}
        if result:
            account["userId"] = result.user_id
            account["username"] = result.login_name
            account["realName"] = result.user_name
            account["avatar"] = result.user_avatar
            account["desc"] = result.user_desc
            account["homePath"] = ''
            account["roles"] = ['super']
        return account


def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
    """
        根据登录信息创建当前用户token
        :param data: 登录信息
        :param expires_delta: token有效期
        :return: token
    """
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, JwtConfig.SECRET_KEY, algorithm=JwtConfig.ALGORITHM)
    return encoded_jwt
